package com.example.okhttpstudy;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {
    // 饿汉单例
    private static ThreadPoolManager threadPoolManager = new ThreadPoolManager();

    public static ThreadPoolManager getInstance() { return threadPoolManager; }

    // 任务队列
    private LinkedBlockingDeque<Runnable> mQueue = new LinkedBlockingDeque<>();

    // 添加任务
    public void addTask(Runnable runnable) {
        try {
            mQueue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 线程池
    private ThreadPoolExecutor threadPoolExecutor;
    private ThreadPoolManager() {
        threadPoolExecutor = new ThreadPoolExecutor(3, 10, 15, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(5), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
                addTask(runnable);
            }
        });
        threadPoolExecutor.execute(coreThread);
    }

    public Runnable coreThread = new Runnable() {
        Runnable runn = null;
        @Override
        public void run() {
            while (true) {
                try {
                    runn = mQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                threadPoolExecutor.execute(runn);
            }
        }
    };
}
